package setup;

import utils.Var;
import utils.DBConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;

import question.Classify;
import question.ClassifyInfo;
import interceptor.InjectConnection;
import account.AccountUtils;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-6-20
 * Time: 21:53:40
 */
public class SetupAction {

  private Connection con;

  @InjectConnection(autoCommit = DBConnection.AutoCommiteOff)
  public void setCon(Connection con) {
    this.con = con;
  }

  private KmSettingInfo settingInfo;

  public String setting() throws Exception {
    KmSetting.delSetting(con, settingInfo.getKmID());
    KmSetting.addSetting(con, settingInfo);

    return Var.ACTION_SUCCESS;
  }

  public KmSettingInfo getSettingInfo() {
    return settingInfo;
  }

  public void setSettingInfo(KmSettingInfo settingInfo) {
    this.settingInfo = settingInfo;
  }

  public String setup() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (!AccountUtils.hasRight(session, Var.RIGHT_SETUP)) throw new Exception("deny!");

    HttpServletRequest request = ServletActionContext.getRequest();
    int kmID = Integer.parseInt(request.getParameter("kmID"));

    List<SetupInfo> list = new ArrayList<SetupInfo>();
    List<ClassifyInfo> clist = Classify.getYdList(con, kmID);
    for (ClassifyInfo cinfo : clist) {
      int sSum = request.getParameter("s_" + cinfo.getCid()) == null ? 0 : Integer.parseInt(request.getParameter("s_" + cinfo.getCid()));
      int mSum = request.getParameter("m_" + cinfo.getCid()) == null ? 0 : Integer.parseInt(request.getParameter("m_" + cinfo.getCid()));
      int tSum = request.getParameter("t_" + cinfo.getCid()) == null ? 0 : Integer.parseInt(request.getParameter("t_" + cinfo.getCid()));

      SetupInfo setupInfo = new SetupInfo(cinfo.getCid(), sSum, mSum, tSum);
      list.add(setupInfo);
    }

    Setup.delSetup(con, kmID);
    Setup.addSetup(con, list);
    return Var.ACTION_SUCCESS;
  }
}
